﻿using ET.CommonLibrary;
using ET.DBCommon.DAL;
using ET.DBCommon.Model;
//using ET.HeartBeat.SharedLibrary;
//using ET.Score.Service.Interfaces;
//using ET.Score.SharedLibrary.Wcf;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Management;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace RadioStationPOC
{
    /// <summary>
    /// Login.xaml 的交互逻辑
    /// </summary>
    public partial class Login : Window
    {
        public Login()
        {
            InitializeComponent();
        }
        //HeartBeatInvoker<IHeartBeatService> MyHeartBeatInvoker;
        //HeartBeatCallBack server = null;
        //IAccountManageService client = null;
        //AccountServiceCallBack callbackInstance = null;
        /// <summary>
        /// 登录标志位
        /// </summary>
        public static bool LoginStatus { get; set; }
        /// <summary>
        /// 用户ID
        /// </summary>
        public static string userId;
        /// <summary>
        /// 用户名称
        /// </summary>
        public static string username;
        /// <summary>
        /// 角色Id
        /// </summary>
        public static string postId;
        /// <summary>
        /// 考核Id
        /// </summary>
        public static int examId;
        //登录事件委托
        public delegate void EventHandle(object sender, RoutedEventArgs e);
        public event EventHandle LogOnClick;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //string ipAdress = ConfigurationManager.AppSettings["HeartBeatService"];
            //string UserName = ConfigurationManager.AppSettings["UserName"];
            //server = new HeartBeatCallBack();
            //server.MessageReceived += Server_MessageReceived;
            //MyHeartBeatInvoker = HeartBeatInit.HeartBeatInitService(server, ipAdress, UserName);


            //string EndPoint = ConfigurationManager.AppSettings["AccountService"];
            //callbackInstance = new AccountServiceCallBack();
            //callbackInstance.MessageReceived += CallbackObject_MessageReceived;
            //client = WCFHelper.CreateDuplexClient<IAccountManageService, AccountServiceCallBack>(EndPoint, callbackInstance);
            //if (client != null)
            //{
            //    AccountServiceProvider.Get_Instance().helper = client;

            //    // AccountServiceProvider.Get_Instance().UserLogin("lukun", "123456");
            //}
            Task.Run(() =>
            {
                while (true)
                {
                    try
                    {
                        if (LoginStatus)
                        {
                            this.Dispatcher.Invoke(() =>
                            {
                                logonButton.IsEnabled = true;
                                if (!this.Topmost)
                                {
                                    //add by hqy 窗体最前
                                    //IntPtr handle = new WindowInteropHelper(this).Handle;
                                    //SetWindowPos(handle, HWND_TOPMOST, 0, 0, this.Width, this.Height, 0x4000 | 0x0001 | 0x0002);
                                    //this.Topmost = true;
                                }
                            });
                        }
                    }
                    catch (Exception ex)
                    { }

                    Thread.Sleep(1000);
                }
            });
            //在第二个屏幕上显示
            System.Windows.Forms.Screen[] _screens = System.Windows.Forms.Screen.AllScreens;
            System.Windows.Forms.Screen s = System.Windows.Forms.Screen.AllScreens[1];
            this.Left = System.Windows.Forms.Screen.AllScreens[1].Bounds.Width+((System.Windows.Forms.Screen.AllScreens[1].Bounds.Width - this.Width) / 2);
            this.Top = ((System.Windows.Forms.Screen.AllScreens[1].Bounds.Height - this.Height) / 2);
            //System.Drawing.Rectangle rect = s.WorkingArea;
            //this.Left = ((rect.Left)); 
            ////this.Left = rect.Left;
            //this.Top = rect.Top;
        }
        //private void CallbackObject_MessageReceived(object sender, GeneralEventArgs<ET.Score.Service.ArgumentExam> e)
        //{
        //    if (e != null)
        //    {
        //        var a = e.Argument;
        //    }
        //}
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            string userNumber = this.txtID.Text.Trim();
            string userPassword = this.txtPaw.Text.Trim();
            if (!string.IsNullOrWhiteSpace(userNumber) && !string.IsNullOrWhiteSpace(userPassword))
            {
                var UserLogin = await Task.Run(() => AccountServiceProvider.Get_Instance().UserLogin(userNumber, userPassword));

                if (!string.IsNullOrWhiteSpace(UserLogin))
                {
                    var userLogin = UserLogin.Split(',').ToList();
                    userId = userLogin[0];
                    username = userLogin[1];
                    examId = int.Parse(userLogin[2]);
                    postId = userLogin[3];
                    LoginStatus = true;
                    this.Hide();

                }
                else
                {
                   // this.DialogResult = Convert.ToBoolean(1);
                    LoginStatus = true;
                    this.Hide();
                }
                    this.txtInfo.Text = "【" + userNumber + "】不是裁判选择参加竞赛的选手！";
            }
            else
            {
                if (string.IsNullOrWhiteSpace(userNumber))
                    this.txtInfo.Text = "请输入选手编号！";
                else if (string.IsNullOrWhiteSpace(userPassword))
                    this.txtPawInfo.Text = "请输入密码！";
                else
                {
                    this.txtInfo.Text = "请输入选手编号！";
                    this.txtPawInfo.Text = "请输入密码！";
                }
            }

        }
        private string NAME;
        /// <summary>
        /// 用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TxtID_TextChanged(object sender, TextChangedEventArgs e)
        {
            NAME = ((System.Windows.FrameworkElement)sender).Name;
            if (popup.IsOpen)
            {
                popup.IsOpen = false;
            }
            //定位popup的位置，使之位于当前单元格的下边缘
            //Image txtAcctName = sender as Image;
            //Point position = txtAcctName.TranslatePoint(new Point(), Checksdatagrid); //获取当前单元格的位置,dgVoucher为DataGrid名称
            //popup.HorizontalOffset = position.X; //设置横坐标偏移量 
            //popup.VerticalOffset = position.Y + txtAcctName.ActualHeight; //纵坐标偏移量+行高（文本框实际显示高度）
            //popup.StaysOpen = false;
            //popup.PlacementTarget = txtAcctName;
            popup.StaysOpen = false;
            popup.IsOpen = true;
            if (this.txtInfo.Text.Length > 0)
                this.txtInfo.Text = "";
            //if (this.txtInfo.Text.Length > 0)
            //    this.txtInfo.Text = "";
        }
        /// <summary>
        /// 密码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtPaw_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (this.txtPawInfo.Text.Length > 0)
                this.txtPawInfo.Text = "";
        }
        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void signoutButton_Click(object sender, RoutedEventArgs e)
        {
            //server.MessageReceived -= Server_MessageReceived;
            //MyHeartBeatInvoker.Stop();
            this.Close();

        }

        /// <summary>
        /// 回车
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtPaw_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                if (LoginStatus)
                {
                    if (LogOnClick == null)
                    {
                        LogOnClick += new EventHandle(Button_Click);
                    }
                    LogOnClick(sender, e);
                }
            }
        }
        /// <summary>
        /// 移动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DockPanel_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }

        private void lstStartHour_MouseUp(object sender, MouseButtonEventArgs e)
        {
            lstStartHour = sender as ListBox;
            if (lstStartHour == null || lstStartHour.SelectedItem == null)
                return;
            else
            {
                var model = lstStartHour.SelectedItem as RoleModel;
                txtID.Text = model.RoleName;
            }
        }
        private void Window_Closed(object sender, EventArgs e)
        {
            //server.MessageReceived -= Server_MessageReceived;
            //MyHeartBeatInvoker.Stop();
            this.Close();
            Environment.Exit(-1);
        }
    }
}
